package com.hsxc.cdz.controller.consoleController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.mgmt.GlobalManager;
import com.hsxc.cdz.trans.bill.CacheTrade;
import com.hsxc.cdz.trans.bill.CacheTrade.TradeStatus;
import com.hsxc.cdz.trans.payment.gzhpay.PrePay;

import net.sf.json.JSONObject;

/**
 * 公众号进行充电并下单需要openid
 * 
 * @author 作者: 陈钊
 * @version 创建时间：2016年6月24日 下午3:30:27 类说明 ：
 */
@Controller
@RequestMapping("/api")
public class ChargeController {

	Logger logger = LoggerFactory.getLogger(ChargeController.class);

	@RequestMapping(value = "/chargerequest", method = RequestMethod.POST)
	@ResponseBody
	public Object charge(@RequestBody String params, HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse) {

		logger.info("CHARGE REQUEST IS STARTING");
		String appID = null;
		String pileID = null;

		JSONObject jsonObjectr = new JSONObject();
		org.json.JSONObject jsonObject = null;
		try {
			httpServletRequest.setCharacterEncoding("UTF-8");
			httpServletResponse.setCharacterEncoding("UTF-8");
			logger.info("CHARGE PARAMS IS " + params);
			String pa = java.net.URLDecoder.decode(params, "utf-8");
			jsonObject = new org.json.JSONObject(pa);

			appID = (String) jsonObject.get("appid");
			pileID = (String) jsonObject.get("pileid");
			String openid = (String) jsonObject.get("openid");
			// myUser.setDriveLicenNO(openid);
			logger.info("appid==" + appID);
			logger.info("openid==" + openid);
			logger.info("pileid==" + pileID);
			if (appID != null && pileID != null && openid != null) {
				logger.info("appid==" + appID);
				logger.info("openid==" + openid);
				logger.info("pileid==" + pileID);

				CacheTrade cacheTrade = GlobalManager.tradeManager.getTradeByOpenId(openid);
				if (cacheTrade == null) {
					int result = GlobalManager.tradeManager.createTrade(pileID, openid, 1);
					if (result == 3) {
						jsonObjectr.put("code", 1);
						jsonObjectr.put("re", GlobalManager.tradeManager.getTradeByOpenId(openid).getTid());
					} else if (result == 0) {
						jsonObjectr.put("code", 2);
						jsonObjectr.put("re", "电桩已经被占用");
					} else if (result == 2) {
						jsonObjectr.put("code", 3);
						jsonObjectr.put("re", "电桩未连枪");
					} else if (result == 1) {
						jsonObjectr.put("code", 4);
						jsonObjectr.put("re", "电桩故障");
					} else if (result == 4) {
						jsonObject.put("code", 5);
						jsonObject.put("re", "该桩未注册");
					}
				} else if (cacheTrade.getTradeStatus() == TradeStatus.TRADE_STATUS_NOPAY) {
					// 下单
					String tid = cacheTrade.getTid();
					JSONObject jsonObject2 = PrePay.order(tid, openid, httpServletRequest.getRemoteAddr(), 1);
					jsonObjectr.put("code", 6);
					jsonObjectr.put("wxreturn", jsonObject2);
					logger.info("TRADE NO PAY EXITS, INFO IS " + jsonObjectr);
				} else if (cacheTrade.getTradeStatus() == TradeStatus.TRADE_STATUS_ON) {
					// 这里是充电中跳出页面，再次进入
				}
			} else {
				jsonObjectr.put("code", 5);
				jsonObjectr.put("re", "请求参数为空");
				logger.info("appid==" + appID);
				logger.info("openid==" + openid);
				logger.info("pileid==" + pileID);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObjectr;
	}

	/**
	 * 用户信息是从session里拿到的
	 * 
	 * @param tid
	 * @return
	 */
	@RequestMapping(value = "/rechargerequest", method = RequestMethod.GET)
	@ResponseBody
	public Object recharge(String tid) {
		JSONObject jsonObjectr = new JSONObject();
		if (tid == null) {
			logger.info("参数tid为空");
			jsonObjectr.put("code", 3);
			jsonObjectr.put("re", "参数tid为空");
			return jsonObjectr;
		}
		CacheTrade cacheTrade = GlobalManager.tradeManager.getTrade(tid);
		if (cacheTrade == null) {
			jsonObjectr.put("code", 4);
			jsonObjectr.put("re", "不存在该交易");
			return jsonObjectr;
		}
		// ChargeManager chargeManager = new ChargeManager();
		// int result = chargeManager.chargeStart(tid);
		int result = GlobalManager.tradeManager.startTrade(tid);
		if (result == 1) {
			jsonObjectr.put("code", 1);
			jsonObjectr.put("re", "成功发送开始充电指令");
		} else {
			jsonObjectr.put("code", 2);
			jsonObjectr.put("re", "开始充电失败");
		}
		while (true) {
			try {
				Thread.sleep(2000);
				CacheTrade cacheTrade2 = GlobalManager.tradeManager.getTrade(tid);
				if (cacheTrade2.getTradeStatus() == TradeStatus.TRADE_STATUS_ON) {
					break;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
		return jsonObjectr;
	}

	@RequestMapping(value = "/chargestop", method = RequestMethod.GET)
	@ResponseBody
	public Object chargeStop(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			HttpSession httpSession) {
		String tid = null;
		String resultString = "0";
		JSONObject jsonObjectr = new JSONObject();
		// MyUser myUser = (MyUser) httpSession.getAttribute("currentUser");
		try {
			httpServletRequest.setCharacterEncoding("UTF-8");
			httpServletResponse.setCharacterEncoding("UTF-8");
			tid = httpServletRequest.getParameter("tid");
			logger.info("TID IS " + tid);
			if (tid == null) {
				jsonObjectr.put("code", 3);
				jsonObjectr.put("re", "参数tid为空");
				logger.info("WHEN REQUEST TO STOP CHARGE,TID IS NULL");
			} else {
				CacheTrade cacheTrade = GlobalManager.tradeManager.getTrade(tid);
				CacheTrade cacheTradeNOPAY = null;
				if (cacheTrade != null) {
					logger.info("CACHE CONTAINS THIS TRADE, TRADE INFO IS " + cacheTrade.toString());
					int result = GlobalManager.tradeManager.stopTrade(tid);
					if (result == 0) {
						logger.info("WAIT FOR BILL CHANGE TO STATUS NOPAY");
						while (true) {
							try {
								Thread.sleep(5000);
								cacheTradeNOPAY = GlobalManager.tradeManager.getTrade(tid);
								if (cacheTradeNOPAY != null
										&& cacheTradeNOPAY.getTradeStatus() == TradeStatus.TRADE_STATUS_NOPAY) {
									break;
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
						// 下单
						JSONObject jsonObject = PrePay.order(tid, cacheTradeNOPAY.getOpenId(),
								httpServletRequest.getRemoteAddr(), 1);
						jsonObjectr.put("code", 1);
						jsonObjectr.put("wxreturn", jsonObject);
						logger.info("PRE PAY SUCCESS,OUT OF --WHILE--");
					} else if (result == 1) {
						jsonObjectr.put("code", 2);
						jsonObjectr.put("re", "停止充电指令发送失败");
					}
				} else {
					logger.info("THERE IS NO TRADE IN CACHE MEMORY");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("PARAMETERS DECODE WITH UTF-8 THROW EXCEPTION");
		}
		logger.info(resultString);
		logger.info(jsonObjectr.toString());
		return jsonObjectr;
	}

}